package com.ywgt;

public class BinarySearch {
    public static void main(String[] args) {
        int [] arr={1,8,10,89,1000,1234};
        //System.out.println(getIndex(arr, 1234));
        int getindex = getindex(arr, 0, arr.length - 1, 2);
        System.out.println(getindex);
    }

    /**
     * 非递归查找
     * @param arr
     * @param val
     * @return
     */
    public static int getIndex(int [] arr,int val){
        int begin=0;
        int end=arr.length-1;
        int mid=-1;
        while(begin<end){
            mid=(begin+end)/2;
            if(val<arr[mid]){
                end=mid-1;
            }
            if(val>arr[mid]){
                begin=mid+1;
            }
            if(val==arr[mid]){
                break;
            }
        }
        return mid;
    }

    /**
     * 递归查找
     * @param arr
     * @param left
     * @param right
     * @param val
     * @return
     */
    public static int getindex(int []arr,int left,int right,int val){
        if(left>right){
            return -1;
        }
        int mid=(left+right)/2;
        if(arr[mid]>val){
           return getindex(arr,left,mid-1,val);
        }
        else if(arr[mid]<val){
           return getindex(arr,mid+1,right,val);
        }else {
            return mid;
        }

    }
}
